package net.jeanhwea.ex1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadURL {
	
	public static int BUFFER_SIZE = 8192;
	
	public void download(URL remoteURL, File localFile) throws IOException{
		HttpURLConnection http = (HttpURLConnection) remoteURL.openConnection();
		HttpURLConnection.setFollowRedirects(false);
		InputStream is = http.getInputStream();
		OutputStream os = new FileOutputStream(localFile);
		
		String type = http.getContentType();
		if(type.startsWith("text")){
			this.downloadText(is, os);
		} else {
			this.downloadBinary(is, os);
		}
		is.close();
		os.close();
		http.disconnect();
	}
	
	public void download(String remoteURL, String localPath) throws MalformedURLException, IOException{
		System.out.println("Download -> start... ");
		System.out.println("Remote URL: " + remoteURL);
		System.out.println("Save to local path: " + localPath);
		download(new URL(remoteURL), new File(localPath));
		System.out.println("\nDownload -> complete\n");
	}
	
	public void downloadText(InputStream is, OutputStream os) throws IOException{
		byte[] lineSep = System.getProperty("line.separator").getBytes();
		int ch = -1;
		boolean inLineBreak = false;
		boolean hadLF = false;
		boolean hadCR = false;
		
		do {
			ch = is.read();
			if(ch != -1){
				if((ch == '\r') || (ch == '\n')){
					inLineBreak = true;
					if(ch == '\r'){
						if(hadCR){
							os.write(lineSep);
						} else {
							hadCR = true;
						}
					}else{
						if(hadLF){
							os.write(lineSep);
						} else {
							hadLF = true;
						}
					}
				} else {
					if(inLineBreak){
						os.write(lineSep);
						hadCR = hadLF = inLineBreak = false;
					}
					os.write(ch);
				}
			}
		}while(ch != -1);
	}
	
	public void downloadBinary(InputStream is, OutputStream os) throws IOException {
		byte[] buffer = new byte[BUFFER_SIZE];
		int size;
		do {
			size = is.read(buffer);
			if(size != -1){
				os.write(buffer);
			}
		} while(size != -1);
	}

	public static void main(String[] args) {
		String remoteURL = "http://www.baidu.com/img/bdlogo.gif";
		String filepath = "D:\\data\\baiduLogo.jpg";
		
		try {
			new DownloadURL().download(remoteURL, filepath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
